<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="来访分类" prop="categoryIds">
        <el-cascader style="width: 100%" v-model="queryParams.categoryIds" :options="categoryOptions" :props="props" collapse-tags clearable
          ><template slot-scope="{ node, data }">
            <span>{{ data.label }}</span>
            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
          </template></el-cascader
        >
      </el-form-item>

      <el-form-item label="属地" prop="ownerArea">
        <el-select v-model="queryParams.ownerArea" placeholder="请选择属地" clearable>
          <el-option v-for="dict in dict.type.biz_area_owner" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="信访人姓名" prop="letterUsername">
        <el-input v-model="queryParams.letterUsername" placeholder="请输入信访人姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="信访人电话" prop="letterTel">
        <el-input v-model="queryParams.letterTel" placeholder="请输入信访人电话" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="来访时间">
        <el-date-picker v-model="letterTime" :clearable="true" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" @input="$forceUpdate()"></el-date-picker>
      </el-form-item>

      <el-form-item label="责任处室" prop="acceptDepts">
        <el-select v-model="queryParams.acceptDepts" placeholder="责任处室" clearable style="width: 100%">
          <el-option v-for="dict in dict.type.biz_letter_resp_dept" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="处理方式" prop="handleMethod">
        <el-select v-model="queryParams.handleMethod" placeholder="处理方式" clearable style="width: 100%">
          <el-option v-for="dict in dict.type.biz_letter_handle_method" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否群访" prop="isGroup">
        <el-select v-model="queryParams.isGroup" placeholder="是否群访" clearable>
          <el-option v-for="dict in dict.type.biz_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否办结" prop="isFinish">
        <el-select v-model="queryParams.isFinish" placeholder="是否办结" clearable>
          <el-option v-for="dict in dict.type.biz_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['record:letter:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['record:letter:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['record:letter:remove']">删除</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport" v-hasPermi="['record:letter:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['record:letter:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-download" size="mini" @click="downloadTemplate('letter_visit_import')">下载导入模板</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="signatureList" stripe :max-height="tableHeight" highlight-current-row highlight-selection-row @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="一级分类" align="center" prop="firstCategoryName" />
      <el-table-column label="二级分类" align="center" prop="secondCategoryName" />
      <!-- <el-table-column label="来件单位" align="center" prop="letterCorp" /> -->
      <el-table-column label="信访人姓名" align="center" prop="letterUsername" />
      <el-table-column label="信访人电话" align="center" prop="letterTel" />
      <el-table-column label="属地" align="center" prop="ownerArea">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.biz_area_owner" :value="scope.row.ownerArea" />
        </template>
      </el-table-column>

      <el-table-column label="是否群访" align="center" prop="isGroup">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.biz_yes_no" :value="scope.row.isGroup" />
        </template>
      </el-table-column>

      <el-table-column label="上访人数" align="center" prop="num" />

      <el-table-column label="处理方式" align="center" prop="handleMethod">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.biz_letter_handle_method" :value="scope.row.handleMethod" />
        </template>
      </el-table-column>
      <el-table-column label="来访时间" align="center" prop="letterTime" width="180" sortable> </el-table-column>

      <el-table-column label="责任处室" align="center" prop="acceptDepts">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.biz_letter_resp_dept" :value="scope.row.acceptDepts" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="经办人" align="center" prop="handleBy" /> -->
      <el-table-column label="具体事项" align="center" prop="letterContent" show-overflow-tooltip />
      <el-table-column label="办理情况" align="center" prop="handleResult" show-overflow-tooltip />
      <!-- <el-table-column label="案件类型" align="center" prop="caseType" /> -->
      <el-table-column label="是否办结" align="center" prop="isFinish">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.biz_yes_no" :value="scope.row.isFinish" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row, 1)" v-hasPermi="['record:letter:edit']">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row, 2)" v-hasPermi="['record:letter:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['record:letter:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改督办事项登记对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="来访分类" prop="categoryIds">
              <!-- <el-input v-model="form.categoryId" placeholder="请输入分类" /> -->
              <el-cascader style="width: 100%" v-model="form.categoryIds" :options="categoryOptions" :props="{ expandTrigger: 'hover' }" clearable></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="属地" prop="ownerArea">
              <el-select v-model="form.ownerArea" placeholder="请选择属地" clearable style="width: 100%">
                <el-option v-for="dict in dict.type.biz_area_owner" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="信访人姓名" prop="letterUsername">
              <el-input v-model="form.letterUsername" placeholder="请输入信访人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="信访人身份证号" prop="letterCardno">
              <el-input v-model="form.letterCardno" placeholder="请输入信访人身份证号" maxlength="18" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="信访人电话" prop="letterTel">
              <el-input v-model="form.letterTel" placeholder="请输入电话" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="处理方式" prop="handleMethod">
              <el-select v-model="form.handleMethod" placeholder="信访目的" clearable style="width: 100%">
                <el-option v-for="dict in dict.type.biz_letter_handle_method" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="责任处室" prop="acceptDepts">
              <el-select multiple v-model="form.acceptDepts" placeholder="责任处室" clearable style="width: 100%">
                <el-option v-for="dict in dict.type.biz_letter_resp_dept" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="经办人" prop="handleBy">
              <el-input v-model="form.handleBy" placeholder="请输入经办人" />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="是否办结" prop="isFinish">
              <el-select v-model="form.isFinish" placeholder="是否办结" clearable style="width: 100%">
                <el-option v-for="dict in dict.type.biz_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select> </el-form-item
          ></el-col>
        </el-row>
        <el-form-item label="办结时间" v-if="form.isFinish == 1" prop="finishTime">
          <el-date-picker style="width: 100%" clearable v-model="form.finishTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择办结时间"> </el-date-picker>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="" prop="num">
              <span slot="label">
                <el-tooltip content="上访人数5人以上（含5人）属于群访" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
                上访人数
              </span>

              <el-input-number v-model="form.num" :min="1" :max="1000" @change="setGroup"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否群访" prop="isGroup">
              <el-radio-group v-model="form.isGroup" disabled>
                <el-radio-button v-for="dict in dict.type.biz_yes_no" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="信访情况">
              <editor v-model="form.letterContent" :min-height="120" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="办理情况" prop="handleResult">
              <editor v-model="form.handleResult" :min-height="120" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="来访时间" prop="letterTime"> <el-date-picker style="width: 100%" clearable v-model="form.letterTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择来信时间"> </el-date-picker> </el-form-item>
        <!-- <el-row>
          <el-col :span="24">
            <el-form-item label="具体事项">
              <editor v-model="form.letterContent" :min-height="120" />
            </el-form-item>
          </el-col>
        </el-row>-->
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="signRemark">
              <el-input v-model="form.signRemark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="view == 2" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport + '&importType=' + upload.importType" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :on-error="handleFileError" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <div class="el-upload__tip" slot="tip">
            <!-- <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的数据 -->
            <!-- <el-divider content-position="center">台账月份</el-divider>
            <el-date-picker
              v-model="upload.billMonth"
              type="month"
              placeholder="选择月"
              value-format="yyyy-MM"
            >
            </el-date-picker> -->
          </div>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSignature, getSignature, delSignature, addSignature, updateSignature } from "@/api/hades/record/letter";
import { treeselect } from "@/api/hades/category/category";
import { getToken } from "@/utils/auth";

export default {
  name: "visit",
  dicts: ["biz_letter_handle_method", "biz_letter_resp_dept", "biz_whether_category", "biz_area_owner", "biz_yes_no", "biz_letter_handle_method"],
  data() {
    return {
      props: { multiple: true },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 督办事项登记表格数据
      signatureList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false, // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        billMonth: "",
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/letter/import/importData",
        importType: "",
        categoryIds: [],
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        deptId: null,
        letterUsername: null,
        letterTime: null,
        source: 3,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        categoryIds: [{ required: true, message: "请选择来访分类", trigger: "change" }],
        letterCorp: [{ required: true, message: "来件单位不能为空", trigger: "blur" }],
        ownerArea: [{ required: true, message: "属地不能为空", trigger: "blur" }],
        letterUsername: [{ required: true, message: "信访人姓名不能为空", trigger: "blur" }],
        // letterCardno: [
        //   {
        //     required: true,
        //     message: "信访人身份证号不能为空",
        //     trigger: "blur",
        //   },
        // ],
        letterTel: [{ required: true, message: "信访人电话不能为空", trigger: "blur" }],
        letterContent: [{ required: true, message: "具体事项不能为空", trigger: "blur" }],
        handleContent: [{ required: true, message: "办理要求不能为空", trigger: "blur" }],
        responsibilityDept: [{ required: true, message: "责任处室不能为空", trigger: "blur" }],
        handleBy: [{ required: true, message: "经办人不能为空", trigger: "blur" }],
        handleMethod: [{ required: true, message: "处理方式", trigger: "blur" }],
        handleResult: [{ required: true, message: "办理情况不能为空", trigger: "blur" }],
      },
      categoryOptions: [],
      view: 2,
    };
  },

  computed: {
    tableHeight() {
      return window.innerHeight - 250;
    },
  },
  created() {
    this.getList();
    this.getCategoryList();
  },
  methods: {
    setGroup() {
      if (this.form.num != "" && this.form.num >= 5) {
        this.form.isGroup = 1;
      } else {
        this.form.isGroup = 0;
      }
    },
    /** 查询分类列表 */
    getCategoryList() {
      treeselect().then((response) => {
        this.categoryOptions = response.data;
      });
    },
    /** 查询督办事项登记列表 */
    getList() {
      this.loading = true;
      this.addDateRange(this.queryParams, this.letterTime, "LetterTime");
      listSignature(this.queryParams).then((response) => {
        this.signatureList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        categoryId: null,
        letterCorp: null,
        deptId: null,
        letterUsername: null,
        letterContent: null,
        handleContent: null,
        letterTime: null,
        responsibilityDept: null,
        handleBy: null,
        handleResult: null,
        caseType: null,
        serialNumber: null,
        signRemark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        num: null,
        isGroup: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.letterTime = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.view = 2;
      this.reset();
      this.open = true;
      this.title = "添加来访事项登记";
    },
    /** 修改按钮操作 */
    handleUpdate(row, view) {
      this.view = view;
      this.reset();
      const id = row.id || this.ids;
      getSignature(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改来访事项登记";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.source = 3;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateSignature(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSignature(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除督办事项登记编号为"' + ids + '"的数据项？')
        .then(function () {
          return delSignature(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "record/letter/export",
        {
          ...this.queryParams,
        },
        `signature_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
      this.upload.importType = "VISIT";
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 50vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    handleFileError(err, file, fileList) {},
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    downloadTemplate(command) {
      let a = document.createElement("a");
      a.href = `/static/` + command + `.xlsx`;
      a.download = command + ".xlsx";
      a.click();
    },
  },
};
</script>
